package com.zy.list.list

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.zy.list.DIYLayoutMainActivity
import com.zy.list.ListConstant.ARG_FILE_ID
import com.zy.list.ListConstant.ARG_OPEN_FILE_MODE
import com.zy.list.ListConstant.MODE_TYPE_EDIT
import com.zy.list.ListConstant.MODE_TYPE_SHOW
import com.zy.list.R

class OpenFileSelectFragment : BottomSheetDialogFragment() {

    private var fileId = 0L

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            fileId = it.getLong(ARG_FILE_ID)
        }
    }

    private fun openFileMode(mode: Int) {
        //打开文件
        startActivity(
            Intent(
                this.context,
                DIYLayoutMainActivity::class.java
            ).apply {
                putExtra(ARG_FILE_ID, fileId)
                putExtra(ARG_OPEN_FILE_MODE, mode)
            })
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        val view = inflater.inflate(
            R.layout.dialog_fragment_open_file_select_mode_layout,
            container,
            false
        )
        view.findViewById<View>(R.id.open_file_edit).setOnClickListener {
            dismissAllowingStateLoss()
            openFileMode(MODE_TYPE_EDIT)
        }

        view.findViewById<View>(R.id.open_file_show).setOnClickListener {
            dismissAllowingStateLoss()
            openFileMode(MODE_TYPE_SHOW)
        }
        return view
    }

    companion object {

        fun show(parentFragmentManager: FragmentManager, fileId: Long = 0) {
            val ft: FragmentTransaction = parentFragmentManager.beginTransaction()
            val prev: Fragment? = parentFragmentManager.findFragmentByTag("OpenFileSelect")
            if (prev != null) {
                ft.remove(prev)
            }
            ft.addToBackStack(null)
            val newFragment: DialogFragment = OpenFileSelectFragment().apply {
                arguments = Bundle().apply {
                    putLong(ARG_FILE_ID, fileId)
                }
            }
            newFragment.show(ft, "OpenFileSelect")
        }
    }
}